<?php

namespace app\api\controller;

use app\api\model\User;
use app\api\model\UserToken;
use think\Controller;

class Login extends Controller
{
    /**
     * 登录接口
     * params username password
     * @return void
     */
    public function index()
    {
        if (!request()->isPost()) {
            return fail(INVALID_REQUEST, '无效的请求');
        }
        $userNumber = input("?post.user_number") ? input('post.user_number') : '';
        $password = input('?post.password') ? input('post.password') : '';
        if (!$userNumber || !$password) {
            return fail(LOGIN_FAIL, '用户名或者密码错误');
        }
        $user = User::queryByUserNumber($userNumber);
        if (!$user) {
            return fail(USER_NOT_EXIST, '用户不存在');
        }
        $verifyResult = User::comparePwd($password, $user['password']);
        if (!$verifyResult) {
            return fail(LOGIN_FAIL, '用户名或者密码错误');
        }
        $token = UserToken::createToken($user);
        unset($user['password']);
        unset($user['salt']);
        $user['x-token'] = $token;
        return success($user);
    }

}